package com.pxl.springbootinit.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pxl.springbootinit.model.entity.ItemLogistics;
import com.pxl.springbootinit.model.entity.User;
import com.pxl.springbootinit.model.enums.LogisticsStatusEnum;
import com.pxl.springbootinit.service.ItemLogisticsService;
import com.pxl.springbootinit.service.UserService;
import com.pxl.springbootinit.service.impl.UserServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 模拟物流运行
 *
 * @author MADAO
 * @create 2024 - 12 - 23 8:36
 */
@Slf4j
@Component
public class ScheduledTaskRunning {

    @Resource
    private ItemLogisticsService itemLogisticsService;

    @Resource
    private UserService userService;

    // 每小时执行一次
//    @Scheduled(cron = "0 0 * * * ?")
    @Scheduled(cron = "0 * * * * ?")    // 每分钟执行一次
    public void mockLogisticsRunning() {
        log.info("定时任务启动，模拟物流运行.....");
        QueryWrapper<ItemLogistics> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("logistics_status", LogisticsStatusEnum.PENDING.getValue());
        queryWrapper.or().eq("logistics_status", LogisticsStatusEnum.IN_TRANSIT.getValue());
        List<ItemLogistics> itemLogistics = itemLogisticsService.list(queryWrapper);
        itemLogistics.forEach(item -> {
            if (item.getCreatedTime() != null) {
                Date now = new Date();
                long diffInMillis = Math.abs(now.getTime() - item.getCreatedTime().getTime());
                long diff = diffInMillis / (60 * 60 * 1000); // 转换为小时
                System.out.println("diff: " + diff);
                //TODO：模拟物流更新，如果有需要，之后可调用高德API修改
                if (diff > 48) {    // 超过48小时，改为已送达
                    Long receivedId = item.getReceivedId();
                    User user = userService.getById(receivedId);
                    item.setCurrentLocation(user.getAddress());
                    item.setLogisticsStatus(LogisticsStatusEnum.DELIVERED.getValue());
                    itemLogisticsService.updateById(item);
                } else if (diff > 3) { // 超过3小时，改为运输中
                    item.setLogisticsStatus(LogisticsStatusEnum.IN_TRANSIT.getValue());
                    item.setCurrentLocation("运输路上");
                    itemLogisticsService.updateById(item);
                }
            }
        });
    }

    @Scheduled(cron = "0 0 0 * * ?")
    public void resetUserActiveInfo(){
        userService.resetUserActiveInfo();
    }

}
